package com.pronhub.luowowo.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.pronhub.luowowo.member.domain.UserInfo;
import com.pronhub.luowowo.service.IUserInfoRedisService;
import com.pronhub.luowowo.util.Rediskey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {
    @Autowired
    private StringRedisTemplate template;

    /**
     *
     * @param key Redis的钥匙
     * @param code  验证码
     * @param time  Redis存活的时间
     */
    @Override
    public void saveVerifCode(String key, String code, int time) {
        template.opsForValue().set(key, code, time, TimeUnit.MINUTES);
    }

    /**
     * 根据Key来得到想的值
     * @param key 钥匙
     * @return 字符串 需要自己转
     */
    @Override
    public String getCodeByKey(String key) {
        return template.opsForValue().get(key);
    }

    /**
     * 存东西
     * @param   token 钥匙Key
     * @param userStr   内容
     */
    @Override
    public void saveUserInfoByToken(String token, String userStr,int time) {
        template.opsForValue().set(token,userStr,time,TimeUnit.MINUTES);
    }

    /**
     * 根据ID来延长时间
     * @param token
     */
    @Override
    public void increaseTimeByKey(String token) {
        template.expire(token, Rediskey.USER_LOGIN.getTime().intValue(),TimeUnit.MINUTES);
    }

    /**
     * 根据钥匙来得到UserInfo
     * @param token
     * @return
     */
    @Override
    public UserInfo getUserInfoByToken(String token) {
        if (token ==null){
            return null;
        }
        String UserStr = template.opsForValue().get(token);
        if (UserStr == null){
            return null;
        }else {
            //延长Key的时间
            template.expire(token, Rediskey.USER_LOGIN.getTime().intValue(),TimeUnit.MINUTES);
            UserInfo userInfo = JSON.parseObject(UserStr, UserInfo.class);
            return userInfo;
        }
    }
}
